/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package schoolLink;

import com.sun.lwuit.Command;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Admin
 */
public class SchoolLink extends javax.microedition.midlet.MIDlet implements ActionListener, HTTPInterface, Runnable {

    public String appNAme = "School Link";
    private Function function;
    public RMSManager rmsManager;
    
    private HTTPconnect myConnection;
    private String mainLink;
    public LoginForm loginForm;
    public MainForm mainForm;
    private int mStyle = -1;
    private boolean mConnect = false;
    private Timer timer;
    private TestTimerTask task;
    private int timerCount = 0;
    private int timerMiliset = 1000;
    public Form progressForm;
    public Progress p1;
    
    
    public String userName = "84984819125";
    public String password = "12345625";
    
    public Toast toast;
            
    // private Dialog progressdialog;
    /**
     * Init
     */
    public SchoolLink() {

    }

    private class TestTimerTask extends TimerTask {

        public final void run() {
            timerCount++;
            System.out.println(timerCount);
            //form.append("Timer Execute Count: " + ++count + "\n");
        }
    }

    public void startApp() {
        //init the LWUIT Display
        Display.init(this);



//        // Setting the application theme is discussed
//        // later in the theme chapter and the resources chapter
//        try {
//              Resources r = Resources.open("/myresources.res");
//              UIManager.getInstance().setThemeProps(
//                r.getTheme(r.getThemeResourceNames()[0])
//               );
//             } catch (java.io.IOException e) {
//        }

        try {
            //open the resource file
            //get and set the theme
            Resources r = Resources.open("/LWUITtheme1.res");
            UIManager.getInstance().
                    setThemeProps(r.getTheme(r.getThemeResourceNames()[0]));
        } catch (java.io.IOException e) {
            //if there is a problem print a message on console
            //in this case default settings will be used
            System.out.println("Unable to get Theme " + e.getMessage());
        }
        function = new Function();
        rmsManager = new RMSManager(function);

        myConnection = new HTTPconnect();
        myConnection.setInterface(this);

        loginForm = new LoginForm(this);
        mainForm = new MainForm(this);

        loginForm.initForm();
        //mainForm.mainFormInit();
        
        //showProgressBar();
        
        //loginFormInit();
    }
//    /**
//     *
//     * @param message
//     */
//    public void showWaitScreen(String message) {
//        progressdialog = new Dialog(appNAme);
//        progressdialog.setLayout(new BorderLayout());
////        Command cmdOk = new Command("Đồng ý", 1) {
////            public void actionPerformed(ActionEvent evt) {
////                //destroyApp(true);
////            }
////        };
//        Command cmdCancel = new Command("Hủy", 2) {
//            public void actionPerformed(ActionEvent evt) {
//                //String[] s = {"1", "2", "3"};
//                //updateInfor(s);
//            }
//        };
//        //dialog.addComponent(new Label(Constant.STRING_APP_CONFIRM_EXIT)); 
//        TextArea textArea = null;
//        textArea = new TextArea(message);
//        textArea.setSingleLineTextArea(false);
//        textArea.setGrowByContent(true);
//        textArea.setFocusable(false);
//        progressdialog.addComponent(BorderLayout.CENTER, textArea);
//
////        dialog.addCommand(cmdOk);
//        progressdialog.addCommand(cmdCancel);
//        progressdialog.show();              
//    }

//    public void showProgressBar() {
//
//        progressForm = new Form("Đang tải dữ liệu ...");
//        progressForm.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
//        p1 = new Progress();
//        //progressForm.addComponent(new Label("Drawn"));
//        progressForm.addComponent(p1);
//        progressForm.show();
//        new BackgroundTask() {
//            public void performTask() {
//                System.out.println("runing ..");
//                byte b = 0;
//                while (true) {
//                    b++;
//                    try {
//                        p1.setProgress(b);
//                        Thread.sleep(50);
//                        
//                    } catch (InterruptedException ex) {
//                        ex.printStackTrace();
//                    }
//                    if (b > 100) {
//                        b = 0;
//                    }
//                }
//            }
//        }.start();
//    }
    //-----------------------------------List-----------------------------------  
    
    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        rmsManager.onClose();
        notifyDestroyed();
    }

    public void actionPerformed(ActionEvent ae) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println(ae.toString());
    }

    //---------------------------ket noi Internet-------------------------------
    public boolean initForConnect(int type, String[] s) {
        //if (mConnect) {
        //    return false;
        //}
        mStyle = type;
        switch (mStyle) {
            case Constant.ACTION_LOGIN_LOGIN:
                mainLink = function.format(Constant.URL_LOGIN_LOGIN, new String[]{s[0], s[1]});
                break;
            case Constant.ACTION_MAIN_LIST:
                mainLink = function.format(Constant.URL_MAIN_LISTNEWS, new String[]{s[0], s[1]});
                break;
            default:
                break;
        }

        new Thread(this).start();
        return true;

    }
//    private Progress p;

    public void startConnect() {
        toast = new Toast("Đang tải dữ liệu ...", Toast.TIME_WAIT);
        
//        timer = new Timer();
//        task = new TestTimerTask();
//        timerCount = 0;
//        timer.schedule(task, timerMiliset);
        
       // mConnect = true;
        //showProgressBar();
        
//        showWaitScreen("123");
//        //WAIT CURSOR   
//        new BackgroundTask() {
//            public void performTask() {
//                for (byte b = 0; b <= 100; b++) {
//                    try {
//                        p.setProgress(b);
//                        Thread.sleep(100);
//                    } catch (InterruptedException ex) {
//                        ex.printStackTrace();
//                    }
//                }
//            }
//        }.start();

        //throw new UnsupportedOperationException("Not supported yet.");
    }

    public void stopConnect(String result) {
        toast = new Toast("Tải xong ...", Toast.TIME_SHORT);
        //toast.removeDialog();
       // mConnect = false;
//        progressdialog.dispose();
        //progressForm.dispose();
        result = result.trim();
//        timer.cancel();
        //throw new UnsupportedOperationException("Not supported yet.");
        switch (mStyle) {
            case Constant.ACTION_LOGIN_LOGIN:
                String[] s = function.splitString(result, "|");
                loginForm.onStopConnect(s[0]);
                break;
            case Constant.ACTION_MAIN_LIST:                                  
                
                rmsManager.addNews(new News(Constant.RMW_NEWS_CHAR_NEW, "khong biet vi sao5 789 123456 890 2345678 01234567 901234 67890 23 45678 90123 45678 9012 3456 78901 234 56 78901 234 567 890 12345 678 901234 567 8901 2345 67 het"));
                rmsManager.addNews(new News(Constant.RMW_NEWS_CHAR_NEW, "test thong tin 78 01234567 901234 67890 23 45678 90123"));
                rmsManager.addNews(new News(Constant.RMW_NEWS_CHAR_NEW, "ngay mung 9/5 khai giang 234 67890 23 45678 90123 45678 9012 3456 78901"));
                rmsManager.addNews(new News(Constant.RMW_NEWS_CHAR_NEW, "hop phu huynh 2345678 01234567 901234 67890 23 45678 90123 45678 9012"));

                mainForm.updateInfor(Constant.ERROR_LIST_SUCCESS);
                
                
                //                s = splitString(result, "|");
//                if (s.length >= 2) {
//                    int error = Integer.parseInt(s[0]);                    
//                    if (error == 0) {
//                        int total = Integer.parseInt(s[1]);
//                        if (total>0){
//                            String[] a = new String[s.length - 2];
//                            for (int i = 0; i < a.length; i++) {
//                                a[i] = s[i + 2];
//                            }
//                            mainForm.updateInfor(Constant.ERROR_LIST_SUCCESS, a);
//                        }else{
//                            mainForm.updateInfor(Constant.ERROR_LIST_NULL,null);
//                        }
//                    }
//                }
                
                
                break;

            default:
                break;
        }
        System.out.println(result);
        
    }

    
    public boolean getConnectState() {
        return mConnect;
    }

    public void httpError(int error) {
        toast.removeDialog();
        //throw new UnsupportedOperationException("Not supported yet.");
       // mConnect = false;
        // System.out.println("error: " + error); 
        String mess = "";
        switch (error) {
            case HTTPInterface.ERROR_CONNECT_INTERNET_FAIL:
                mess = "Kết nối Internet lỗi!";
                break;
            case HTTPInterface.ERROR_CLOSE_CONNECTION_FAIL:
                mess = "Đóng kết nối Internet lỗi!";
                break;
        }
        new Toast(mess, Toast.TIME_SHORT);

        //progressdialog.dispose();
    }

    public void run() {
        //S_total_out+=link.toCharArray().length;
        System.out.println("all: " + mainLink);
        myConnection.getData(mainLink);
    }

}